import {
  ref,
  computed,
  onMounted,
  onUnmounted,
  watch,
  nextTick
} from 'vue';
import { useStore } from 'vuex';
import BScroll from '@better-scroll/core';
import Slide from '@better-scroll/slide';

BScroll.use(Slide);

export default function useMiniSlider() {
  const sliderWrapperRef = ref(null);
  const slider = ref(null);

  const store = useStore();
  const fullScreen = computed(() => store.state.fullScreen);
  const playlist = computed(() => store.state.playList);
  const currentIndex = computed(() => store.state.currentIndex);

  const sliderShow = computed(() => {
    // fullScreen为false并且playlist存在的情况下说明mini播放器已经显示
    // !! 双非,转换为布尔类型
    return !fullScreen.value && !!playlist.value;
  });

  onMounted(() => {
    let sliderVal;
    // 如果mini播放器没有显示,goToPage是没有意义的
    // goToPage 基于DOM操作,改变内部层的transform
    // 基于DOM要保证的一点是当前DOM已经渲染的情况下,DOM渲染了,才能正确计算出所在的位置,才能执行goToPage
    watch(sliderShow, async (newSliderShow) => {
      // slider初始化
      if (newSliderShow) {
        await nextTick();
        // watch监听会频繁和执行,但是实例只需要在第一次执行时渲染
        // 如果实例不存在,在初始化,如果存在,则直接refresh
        if (!sliderVal) {
          sliderVal = slider.value = new BScroll(sliderWrapperRef.value, {
            click: true,
            scrollX: true,
            scrollY: false,
            momentum: false,
            bounce: false,
            probeType: 2,
            slide: {
              autoplay: false,
              loop: true
            }
          });
          // pageX横轴当前索引值
          sliderVal.on('slidePageChanged', ({ pageX }) => {
            store.commit('setCurrentIndex', pageX);
            // store.commit('setPlayingState', true);
          });
        } else {
          sliderVal.refresh();
        }
        sliderVal.goToPage(currentIndex.value, 0, 0);
      }
    });

    watch(currentIndex, (newIndex) => {
      if (sliderVal && sliderShow.value) {
        sliderVal.goToPage(newIndex, 0, 0);
      }
    });

    watch(playlist, async (newList) => {
      if (sliderVal && sliderShow.value && newList.length) {
        // 数据的变化到DOM的变化是有一定的时间
        await nextTick();
        // bug: 清空列表之后playlist的长度为0,这是执行refresh会报错
        // 需要做一层保护
        sliderVal.refresh();
      }
    });
  });

  onUnmounted(() => {
    // 判断是因为在mounted中初始化了slider, slider.value才会有值,如果没有初始化的话slider就是null,是没有destroy方法的
    if (slider.value) {
      slider.value.destroy();
    }
  });

  return {
    slider,
    sliderWrapperRef
  };
}
